<template>
<div>
    <div class="top-bar">
        <el-button type="primary" icon="el-icon-edit" @click="addIch()">添加非遗</el-button>
        <el-input
            v-model="searchKeyword"
            placeholder="请输入非遗名称进行搜索"
            style="width: 300px; margin-left: 10px;"
            @keyup.enter="handleSearch"
            clearable>
            <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
        </el-input>
    </div>
    <el-col :span="23" class="data-table">
        <el-table :data="tableData" border style="width: 100%">
            <el-table-column label="ID" width="80px" fixed>
                <template slot-scope="scope">
                    <span>{{ scope.row.ichID }}</span>
                </template>
            </el-table-column>
            <el-table-column label="非遗名称" width="220px" fixed>
                <template slot-scope="scope">
                    <el-popover trigger="hover" placement="top">
                        <p><i style="color:rgb(64,158,255);" class="el-icon-info">非遗名称</i>&nbsp;&nbsp;{{ scope.row.ichName }}</p>
                        <p><i style="color:rgb(64,158,255);" class="el-icon-user">发布者</i>&nbsp;&nbsp;{{ scope.row.ichAuthor }}</p>
                        <p><i style="color:rgb(64,158,255);" class="el-icon-s-comment">非遗介绍</i>&nbsp;&nbsp;{{ scope.row.ichDesc }}</p>
                        <img :src="scope.row.ichPicture" style="height:300px" />
                        <div slot="reference" class="name-wrapper">
                            <span style="color:rgb(64,158,255);">{{ scope.row.ichName }}</span>
                        </div>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column label="图片链接" width="380px">
                <template slot-scope="scope">
                    <span>{{ (scope.row.ichPicture || '').slice(0, 60) + '...'}}</span>
                </template>
            </el-table-column>
            <el-table-column label="发布者" width="150px" sortable>
                <template slot-scope="scope">
                    <span style="margin-left: 10px">{{ scope.row.ichAuthor }}</span>
                </template>
            </el-table-column>
            <el-table-column label="发布时间" width="200px" sortable>
                <template slot-scope="scope">
                    <span style="margin-left: 10px">{{ scope.row.ichDate }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="150px" fixed="right">
                <template slot-scope="scope">
                    <el-button size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-popconfirm confirm-button-text='删除' cancel-button-text='取消' @confirm="handleDelete(scope.$index, scope.row)" icon="el-icon-info" icon-color="red" title="确定删除吗？">
                        <el-button slot="reference" size="mini" type="danger" style="margin-left: 5px;">删除</el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[5, 10]" :page-size="pagesize" background layout="total, sizes, prev, pager, next, jumper" :total="totalCount" style="padding-top:20px">
        </el-pagination>
    </el-col>
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="40%">
        <el-form ref="form" :model="form" :rules='rules' label-width="80px">
            <el-alert v-if="editable" title="管理员无法修改图片内容" type="warning" style="margin-bottom: 20px; margin-top:-20px;"></el-alert>
            <el-form-item label="非遗名称" prop="ichName">
                <el-input v-model="form.ichName"></el-input>
            </el-form-item>
            <el-form-item label="非遗介绍" prop="ichDesc">
                <el-input type="textarea" :rows="3" v-model="form.ichDesc"></el-input>
            </el-form-item>
            <el-form-item v-show=!editable label="添加图片">
                <el-upload class="avatar-uploader" action="http://localhost:8080/uploadPicture" list-type="picture-card" :show-file-list="true" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :auto-upload="false" ref="upload" :on-success="onSuccess" :on-progress="onProgress" :limit="1">
                    <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="imgDialogVisible">
                    <img width="100%" :src="imgURL" alt="">
                </el-dialog>
            </el-form-item>
            <el-form-item label="发布者">
                <el-input v-model=userName :disabled=true></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button v-if="dialogTitle === '添加非遗'" type="primary" @click="handleAddIch('form')">发 布</el-button>
            <el-button v-else type="primary" @click="handleModifyIch('form')">修 改</el-button>
        </span>
    </el-dialog>
</div>
</template>

<style scoped>
.data-table {
    margin-top: 20px;
}
</style>

<script>
const axios = require('axios')
const qs = require('qs')
const ele = require('element-ui')

export default {
    name: 'manageIch',
    data() {
        return {
            currentPage: 1,
            pagesize: 5,
            totalCount: 0,
            searchKeyword: '',
            tableData: [],
            userName: '',
            dialogVisible: false,
            imgDialogVisible: false,

            // 修改非遗时不能编辑图片
            editable: true,
            imgURL: '',
            currentIchID: '',
            dialogTitle: '添加非遗',
            form: {
                ichName: '',
                ichDesc: '',
                ichPicture: ''
            },
            tableData: [],
            rules: {
                ichName: [{ required: true, message: '必填项', trigger: 'blur' }],
                ichDesc: [{ required: true, message: '必填项', trigger: 'blur' }]
            },
        }
    },
    created() {
        if (window.localStorage.getItem('userType') != 'admin') {
            ele.Message.error("你没有管理员权限访问后台，即将跳转到登录页面")
            this.$router.push('/login')
        } else {
            let _this = this
            this.userName = window.localStorage.getItem('userName')
            _this.loadData()
        }
    },
    methods: {
        // 加载数据
        loadData() {
            let _this = this
            axios({
                method: 'get',
                url: 'http://localhost:8080/getIchList',
                params: {
                    searchKeyword: this.searchKeyword,
                    page: this.currentPage,
                    pageSize: this.pagesize
                },
                headers: {
                    'Content-type': 'application/x-www-form-urlencoded'
                }
            }).then(function (response) {
                _this.tableData = response.data.dataList
                _this.totalCount = response.data.totalCount
            }).catch(function (error) {
                console.log(error)
            })
        },
        // 搜索功能
        handleSearch() {
            this.currentPage = 1
            this.loadData()
        },
        handleSizeChange: function (size) { 
            this.pagesize = size;
            this.currentPage = 1
            this.loadData()
        },
        handleCurrentChange: function (currentPage) { 
            this.currentPage = currentPage;
            this.loadData()
        },
        addIch() {
            this.dialogVisible = true
            this.dialogTitle = '添加非遗'
            this.editable = false
        },
        handleEdit(index, row) {
            this.dialogTitle = "修改非遗信息"
            this.dialogVisible = true
            this.editable = true

            this.currentIchID = row.ichID,
            this.form.ichName = row.ichName,
            this.form.ichDesc = row.ichDesc,
            this.form.ichPicture = row.ichPicture
        },
        handleAddIch(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.$refs.upload.submit();
                } else {
                    ele.Message.error("请按要求输入表格内容")
                }
            })
        },
        onSuccess: function (response) {
            if (response.status === "success") {
                this.form.ichPicture = response.imgURL
                let _this = this
                axios({
                    method: 'post', url: 'http://localhost:8080/addIch',
                    headers: { 'Content-type': 'application/x-www-form-urlencoded' },
                    data: qs.stringify({
                        ichName: this.form.ichName,
                        ichDesc: this.form.ichDesc,
                        ichPicture: this.form.ichPicture,
                        ichAuthor: this.userName
                    })
                }).then(function (response) {
                    if (response.data.status == 'success') {
                        ele.Message.success('创建非遗成功')
                        _this.loadData()
                        _this.dialogVisible = false
                    } else {
                        ele.Message.error("创建非遗失败")
                    }
                }).catch(function (error) { console.log(error) })
            } else { ele.Message.error("图像上传失败，请重试") }
        },
        onProgress() {},
        handleRemove(file, fileList) { console.log(file, fileList); },
        handlePictureCardPreview(file) { this.imgURL = file.url },
        handleModifyIch(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let _this = this
                    axios({
                        method: 'post', url: 'http://localhost:8080/updateIch',
                        headers: { 'Content-type': 'application/x-www-form-urlencoded' },
                        data: qs.stringify({
                            ichID: this.currentIchID,
                            ichName: this.form.ichName,
                            ichDesc: this.form.ichDesc,
                            ichPicture: this.form.ichPicture,
                            ichAuthor: this.userName
                        })
                    }).then(function (response) {
                        ele.Message.success('更新非遗数据成功')
                        _this.loadData()
                        _this.dialogVisible = false
                    }).catch(function (error) { console.log(error) })
                } else {
                    this.dialogVisible = true; return false
                }
            })
        },
        handleDelete(index, row) {
            let _this = this
            axios({ method: 'post', url: 'http://localhost:8080/deleteIch',
                headers: { 'Content-type': 'application/x-www-form-urlencoded' },
                data: qs.stringify({ ichID: row.ichID })
            }).then(function (response) {
                ele.Message.success('更新数据成功')
                _this.tableData = response.data.dataList
            }).catch(function (error) { console.log(error) })
        }
    }
}
</script>
